/**
 * @param {character[][]} maze
 * @param {number[]} entrance
 * @return {number}
 */
 var nearestExit = function(maze, entrance) {
    const m = maze.length, n = maze[0].length
    const queue = [entrance]
    const getNext = (pos) => {
        let [x,y] = pos
        const ret = []
        if(x + 1 < m && maze[x+1][y] === '.'){
            ret.push([x+1,y])
        }
        if(x - 1 >= 0 && maze[x-1][y] === '.'){
            ret.push([x-1, y])
        }
        if(y + 1 < n && maze[x][y+1] === '.'){
            ret.push([x, y+1])
        }
        if(y - 1 >= 0 && maze[x][y-1] === '.'){
            ret.push([x, y-1])
        }
        return ret
    }
    let ans = 0
    const visited = new Set()
    while(queue.length){
        ans++
        for(let i = 0, len = queue.length; i<len; i++){
            let cur = queue.shift()
            if(visited.has(cur.toString())){
                continue
            }
            for(let [x,y] of getNext(cur)){
                if(x === 0 || y === 0 || x === m-1 || y === n-1){
                    return ans
                }
                queue.push([x,y])
            }
            maze[cur[0]][cur[1]] = '+'
            visited.add(cur.toString())
        }
    }
    return -1
};